package haoyc.handler;

import haoyc.entity.Message;
import haoyc.utils.GzipUtils;
import haoyc.utils.SwingClient;
import haoyc.utils.TheadPoolFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;

/**
 * @author Memory
 * @version 1.0
 * @date 2021/11/23
 */
@Slf4j
@ChannelHandler.Sharable
public class OperatorHandler extends SimpleChannelInboundHandler<Message> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message message) {
        try {
            byte[] data = message.getAttachment();
            data = GzipUtils.ungzip(data);
            BufferedImage image = ImageIO.read(new ByteArrayInputStream(data));

            JFrame jFrame = SwingClient.getJFrame(ctx, image.getHeight(), image.getWidth());
            JLabel jLabel = SwingClient.getJLabel();
            jFrame.add(jLabel);

            Runnable task1 = () -> {
                jLabel.setIcon(new ImageIcon(image));
                jFrame.repaint();
            };

            TheadPoolFactory.pool.execute(task1);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
